<?php
App::uses('AppController', 'Controller');
/**
 * Customers Controller
 *
 * @property Customer $Customer
 */
class CustomersController extends AppController {
	var $components = array (
			'RequestHandler',
			'Session',
			'Cookie'
	);

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Customer->recursive = 0;
		$this->set('customers', $this->paginate());
        $this->pageTitle = '- Customers';

    }
	
	public function indexdata() {	

        $this->autoRender = false;  
		$output = $this->Customer->GetData();	
		echo json_encode($output);
		
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Customer->exists($id)) {
			throw new NotFoundException(__('Invalid customer'));
		}
		$options = array('conditions' => array('Customer.' . $this->Customer->primaryKey => $id));
		$this->set('customer', $this->Customer->find('first', $options));
		
		$orders = $this->Customer->getorders($id);
		$this->set('Customerorders', $orders);
	}


	
/**
 * add method
 *
 * @return void
 */
	public function add() {
	
		if ($this->request->is('post')) {
		
			// abort if cancel button was pressed
			if (isset( $this->data['Cancel']))
			{
				$this->Session->setFlash(__('Changes were not saved', true));
				//$this->redirect( array( 'action' => 'index' ));
			}
			$this->Customer->create();
			
			//set join_date automatically
			$this->Customer->set('join_date', date('Y-m-d'));
			
			//save activationKey into table. Uncomment when activationKey column is add to table
			$this->Customer->set('activationKey', AuthComponent::password($this->data['Customer']['email']));
			
			
			//captcha related
			//if Component was not loaded throug $components array()
			if(!isset($this->Captcha))	{ 
				$this->Captcha = $this->Components->load('Captcha'); //load it
			}
			
			$this->Customer->setCaptcha($this->Captcha->getVerCode()); //getting from component and passing to model to make proper validation check
			
			
			if ($this->Customer->save($this->request->data)) {
				$this->Session->setFlash(__('Registration completed, '. $this->request->data['Customer']['username']));
				/** ------------- Email activation -------- */
				// Comment below line out if not work
				$this->__sendEmailConfirm($this->Customer->id,$this->request->data['Customer']['customerlink']);
				
				//Create a cart for customer registered
				$this->loadModel('Cart');
				$this->Cart->create();
				$customer_id = $this->Customer->id;
				$this->Cart->save($customer_id);
				
				$this->redirect(array('action' => 'index'));
				
			
			} else {
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.'));
			}
		}
        $genders = $this->Customer->Gender->find('list', array("order" => array("Gender.id" => "desc")));
		$groups = $this->Customer->Group->find('list');
		$this->set(compact('genders', 'groups'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Customer->exists($id)) {
			throw new NotFoundException(__('Invalid customer'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
                    
                        // abort if cancel button was pressed
                        if (isset( $this->data['Cancel']))
                        {
                                $this->Session->setFlash(__('Changes were not saved', true));
                                //$this->redirect( array( 'action' => 'index' ));
                        }
                        
                        //point to object
                        $this->Customer->id = $id;
			if ($this->Customer->save($this->request->data)) {
				$this->Session->setFlash(__('The customer has been saved'));
				$this->redirect(array('action' => 'view', $id));
			} else {
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Customer.' . $this->Customer->primaryKey => $id));
			$this->request->data = $this->Customer->find('first', $options);
		}
		$genders = $this->Customer->Gender->find('list');
		$groups = $this->Customer->Group->find('list');
		$this->set(compact('genders', 'groups'));
                $this->set('customer', $this->Customer->find('first', array('condtions' => array('Customer.id' => $id))));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Customer->id = $id;
		if (!$this->Customer->exists()) {
			throw new NotFoundException(__('Invalid customer'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Customer->delete()) {
			$this->Session->setFlash(__('Customer deleted'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Customer was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
        
/** ---------------------------------------------------------------------- */
        
        public function beforeFilter() {
            parent::beforeFilter();
            
            $this->Auth->autoRedirect = false;

            $this->Auth->allow('login', 'add','search_name','sendForgotPassword');
            
            //$this->Auth->userScope = array('Customer.status_is' == 1);
            
        }
        
        public function login() {

                if ($this->request->is('post')) {
                        if ($this->Auth->login()) {
                                //save last log in time
                                $this->Customer->id = $this->Auth->user('id');
                                $this->Customer->saveField('last_login', DboSource::expression('NOW()'));
                                
                                // If logging in user is admin then display index
                                if ($this->Auth->user('group_id') == '1') {
                                $this->redirect($this->Auth->redirect());
                                } else 
                                // If logging in user is not admin then bring them to their profile
                                {
                                    $this->redirect($this->redirect(array('controller' => 'customers', 'action' => 'view', $this->Auth->user('id'))));
                                }
                        } else {
                            $this->Session->setFlash('An error occurred. Please try again');
                        }   
        }}
        
        
        public function logout() {
                $this->Session->setFlash('You are logged out ' . $this->Auth->user('first_name'));
                $this->redirect($this->Auth->logout());
                $this->Session->delete();
                $this->Session->destroy();
        }
        
        //make sure owner of one profile can only edit his profile
        public function isAuthorized($customer) {
            if ($customer['group_id'] == '1') {
                return true;
            }
            if (in_array($this->action, array('edit', 'delete', 'view', 'resetPassword'))) {
                if ($customer['id'] != $this->request->params['pass']['0']) {
                    return false;
                }
            }
            return true;
        }
        
        /** -------------- end of version 0.8b --------------------------- */
        
        
        public function search() {
            //$this->set('results',$this->Customer->search($this->data['Customer']['q']));
            
            $keyword=$this->request->data['Customer']['keyword']; //get keyword from querystring//
            //used simpme or condition with singe value checking
            //replace ModelName with actual name of your Appmodel
            
            //$this->Session->setFlash($keyword);
            
            $conditions=array('OR'=>array(
                'Customer.id LIKE'=> $keyword,
                'Customer.username LIKE'=> $keyword, 
                'Customer.first_name LIKE'=> $keyword,
                'Customer.last_name LIKE'=> $keyword));

            $this->set('isFound', $this->Customer->find('count',array(
                'conditions'=>$conditions)
                )
            );
            
            $this->set('list', $this->Customer->find('all',array(
                'conditions'=>$conditions)
                )
            );
        }
        
        /** --------------------- end of version 0.8c stable ------------ */
        
        /** --------------------- email validation ---------------------- */
        
        function __sendEmailConfirm($customer_id,$url) {
            App::uses('CakeEmail', 'Network/Email');
        
            $customer = $this->Customer->find('first', array(
                'conditions'=>array(
                    'Customer.id' => $customer_id),
                    'fields'=>array('Customer.id','Customer.email','Customer.username'),
                    'recursive'=>0));
    
            if ($customer == false) {
                //debug(__METHOD__." failed to retrieve Customer data for customer.id: {$customer_id}");
                return false;
            }
            
            $activate_url = $url . $customer['Customer']['id'] . '/' . AuthComponent::password($this->data['Customer']['email']);
            //alternate try
            //$this->set('activate_url', 'http://' . env('SERVER_NAME') . '/customers/activate/' . $customer['Customer']['id'] . '/' . $activatiinHash);
            
            $usernames = $customer['Customer']['username'];
            //alternate try
            //$this->set('usernames', $customer['Customer']['username']);
            
            $email = new CakeEmail();
            $email->from(array('noreply@'.env('SERVER_NAME').".com" =>  'My Site'));
            $email->to($customer['Customer']['email']);
            $email->subject(env('SERVER_NAME') . ' Please confirm your email address');
            $email->template('customer_confirm');
            $email->emailFormat('html');
            $email->viewVars(array(
                'activate_url' => $activate_url,
                'username' => $customer['Customer']['username'])
                );
            return $email->send();
        }

        /** --------------------------- activate account --------------------------- */

            public function activate($customer_id, $activateHash) {


            $customer = $this->Customer->find('first', array(
                    'conditions'=>array(
                        'Customer.id' => $customer_id,
                        'Customer.activationKey' => $activateHash),
                        'fields'=>array('Customer.id','Customer.email','Customer.username'),
                        'recursive'=>0));

            //var_dump($activateHash);

            var_dump($customer_id);    

            if ($customer == true) {
                $this->Customer->id = $customer_id;
                $this->Customer->saveField('status_id', 2);
                $this->Session->setFlash(__('Account has been activated'));
                } else {
                    $this->Session->setFlash('cannot activate');
                }
            }


        /** --------------------------- reset password --------------------------- */
        
        
        public function resetPassword($id = null) {
		if (!$this->Customer->exists($id)) {
			throw new NotFoundException(__('Invalid customer'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
                        $this->request->data['Customer']['id'] = $id;
                    
			if ($this->Customer->save($this->request->data)) {
				$this->Session->setFlash(__('The customer has been saved'));
				$this->redirect(array('action' => 'view', $id));
			} else {
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Customer.' . $this->Customer->primaryKey => $id));
			$this->request->data = $this->Customer->find('first', $options);
		}
		$genders = $this->Customer->Gender->find('list');
		$groups = $this->Customer->Group->find('list');
		$this->set(compact('genders', 'groups'));
                //$this->set('customer', $this->Customer->find('first', array('condtions' => array('Customer.id' => $id))));
	}
        
        
        /** --------------------------- send reset password email --------------------------- */
        
       public function sendForgotPassword() {

		$email = $this->data['Customer']['email'];
		$url = $this->data['Customer']['customerlink'];
		
            App::uses('CakeEmail', 'Network/Email');
        
            $customer = $this->Customer->find('first', array(
                'conditions'=>array(
                    'Customer.email' => $email),
                    'fields'=>array('Customer.id','Customer.email','Customer.username'),
                    'recursive'=>0));

            if ($customer == false) {
                debug(__METHOD__." failed to retrieve Customer data for customer.id: {$email}");
                return false;
            }
             
			$tempPassword = $this->Customer->createTempPassword(7);
            
            $activate_url = $url . $customer['Customer']['id'];
			
            $username = $customer['Customer']['username'];
		    $customer_id = $customer['Customer']['id'];       
			
	   
            //assigned $tempPassword to current password
	   
	       $id = $this->Customer->id = $customer_id; 
           $this->Customer->saveField('password',  $tempPassword);

            $email = new CakeEmail();
            $email->from(array('noreply@'.env('SERVER_NAME').".com" =>  'My Site'));
            $email->to($customer['Customer']['email']);
            $email->subject(env('SERVER_NAME') . ' Your requested password at PrettyLittleTreasures.com.au');
            $email->template('customer_reset_password');
            $email->emailFormat('html');
            $email->viewVars(array(
                'activate_url' => $activate_url,
                'tempPassword' => $tempPassword,
                'username' => $username)
                );
			$email->send();
				
			$this->Session->setFlash(__('Please check your email with temporary password to login.'));
			$this->redirect(array('action' => 'login'));
			
//			$this->Session->setFlash(__('Please check your email for the reset password instruction.'));
//			$this->redirect(array('action' => 'index'));
        }
        
        public function captcha() {
            $this->autoRender = false;
            $this->layout='ajax';
            //if Component was not loaded throug $components array()
            if(!isset($this->Captcha)) {
                //load it
                $this->Captcha = $this->Components->load('Captcha', array(
                    'width' => 150,
                    'height' => 50,
                    //possible values : default, random ; No value means 'default'
                    'theme' => 'default', 
                )); 
            }
            $this->Captcha->create();
	}
	/**
	 * Search for customer information
	 * */
	public function search_name() {
		if (isset ( $_REQUEST ["term"] )) {
			$keyword = h ( $_REQUEST ["term"] );
		}
		$search_key = "%$keyword%";
		$conditions = array (
				'OR' => array (
						'Customer.id LIKE' => $search_key,
						'Customer.username LIKE' => $search_key,
						'Customer.first_name LIKE' => $search_key,
						'Customer.last_name LIKE' => $search_key 
				) 
		);
		
		$this->set ( 'isFound', $this->Customer->find ( 'count', array (
				'conditions' => $conditions 
		) ) );
		
		$this->set ( 'list', $this->Customer->find ( 'all', array (
				'conditions' => $conditions 
		) ) );
	}
}